package com.cloudpark.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cloudpark.common.util.Constants;
import com.cloudpark.common.util.DateUtils;
import com.cloudpark.common.util.TimeUtil;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.model.entity.AdminUserRole;
import com.cloudpark.model.entity.Menu;
import com.cloudpark.model.entity.NavMenu;
import com.cloudpark.service.MenuService;
import com.cloudpark.service.UserService;


public class BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;

    /**
     * 左侧菜单点击事件通用方法处理
     * 
     * @param request
     * @param response
     */
    public Menu initMenu(HttpServletRequest request, HttpServletResponse response) {
        isSessionExpire(request, response);
        String navIdStr = request.getParameter("navId");
        String menuIdStr = request.getParameter("menuId");
        Long navId = 0l;
        Long menuId = 0l;
        Menu currMenu = null;
        NavMenu param = new NavMenu();
        param.setStatus(Constants.ENABLE);
        List<NavMenu> navMenus = menuService.findNavMenus(param); // �?��nav
                                                                  // menu菜单
        if (StringUtils.isNotEmpty(menuIdStr)) {
            menuId = Long.valueOf(menuIdStr);
            if (menuId > 0) {
                currMenu = menuService.findMenuById(menuId);
                navId = currMenu.getNavId();
                request.setAttribute("currMenuName", currMenu.getName());
                request.setAttribute("currMenuId", currMenu.getId());
            }
        } else {
            if (StringUtils.isEmpty(navIdStr)) {
                navId = navMenus.get(0).getId();
            } else {
                navId = Long.valueOf(navIdStr);
            }
        }

        // 获取用户具备的菜单权限
        AdminUser adminUser = (AdminUser) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER);
        List<AdminUserRole> userRoles = userService.findRolesByUserId(adminUser.getId());
        List<Long> roleIds = new ArrayList<Long>();
        List<Long> roleMenuIds = new ArrayList<Long>();
        for (AdminUserRole ur : userRoles) {
            roleIds.add(ur.getRoleId());
            roleMenuIds = menuService.findMenuIdsByRoleIds(roleIds);
        }

        // 查找nav下面的一级菜�?
        List<Menu> list = menuService.findMenusByNavId(navId);
        StringBuffer sb = new StringBuffer();
        String navigation = "";

        int i = 0;
        int j = 0;
        for (Menu root : list) {
            if (null == currMenu) {
                if (roleMenuIds.contains(root.getId())) { // 权限筛�?
                    if (root.getIsLeaf() == Constants.CONST_ONE) {
                        if (i == 0 && j == 0) {
                            currMenu = root;
                            request.setAttribute("currMenuId", currMenu.getId());
                            sb.append("<li class=\"active\"><a href=\"").append(root.getUrl()).append("?menuId=")
                                    .append(root.getId());
                        } else {
                            sb.append("<li><a href=\"").append(root.getUrl()).append("?menuId=").append(root.getId());
                        }
                        sb.append("\"><span class=\"fa ").append(root.getIcon())
                                .append("\"></span> <span class=\"xn-text\">").append(root.getName())
                                .append("</span></a></li>");
                        j++;
                    } else if (root.getIsLeaf() == Constants.CONST_TWO) {
                        List<Menu> children = menuService.findMenusByParentId(root.getId());
                        sb.append("<li class=\"xn-openable\"><a href=\"#\"><span class=\"fa ").append(root.getIcon())
                                .append("\"></span><span class=\"xn-text\">").append(root.getName())
                                .append("</span></a>").append("<ul>");
                        int k = 0;
                        for (Menu child : children) {
                            if (roleMenuIds.contains(child.getId())) { // 权限筛�?
                                if (i == 0 && k == 0) {
                                    currMenu = child;
                                    request.setAttribute("currMenuId", currMenu.getId());
                                    sb.append("<li class=\"active\" ><a href=\"").append(child.getUrl())
                                            .append("?menuId=");
                                } else {
                                    sb.append("<li><a href=\"").append(child.getUrl()).append("?menuId=");
                                }
                                sb.append(child.getId()).append("\"><span class=\"fa ").append(child.getIcon())
                                        .append("\"></span> <span class=\"xn-text\">").append(child.getName())
                                        .append("</span></a></li>");
                                k++;
                            }
                        }
                        sb.append("</ul>").append("</li>");
                    }
                    i++;
                }
            } else {
                if (roleMenuIds.contains(root.getId())) { // 权限筛�?
                    if (root.getIsLeaf() == Constants.CONST_ONE) {
                        if (root.getId().equals(currMenu.getId())) {
                            navigation = "<ul class=\"breadcrumb\"><li class=\"active\">" + root.getName()
                                    + "</li></ul>"; // 导航
                            sb.append("<li class=\"active\"><a href=\"").append(root.getUrl()).append("?menuId=")
                                    .append(root.getId()).append("\"><span class=\"fa ").append(root.getIcon())
                                    .append("\"></span> <span class=\"xn-text\">").append(root.getName())
                                    .append("</span></a></li>");
                        } else {
                            sb.append("<li><a href=\"").append(root.getUrl()).append("?menuId=").append(root.getId())
                                    .append("\"><span class=\"fa ").append(root.getIcon())
                                    .append("\"></span> <span class=\"xn-text\">").append(root.getName())
                                    .append("</span></a></li>");
                        }
                    } else if (root.getIsLeaf() == Constants.CONST_TWO) {
                        List<Menu> children = menuService.findMenusByParentId(root.getId());
                        if (root.getId().equals(currMenu.getParentId())) {
                            navigation = "<ul class=\"breadcrumb\"><li><a>" + root.getName() + "</a></li>"; // 导航
                            sb.append("<li class=\"xn-openable active\"><a href=\"#\"><span class=\"fa ")
                                    .append(root.getIcon()).append("\"></span><span class=\"xn-text\">")
                                    .append(root.getName()).append("</span></a>").append("<ul>");
                            for (Menu child : children) {
                                if (roleMenuIds.contains(child.getId())) { // 权限筛�?
                                    if (child.getId().equals(currMenu.getId())) {
                                        navigation = navigation + "<li class=\"active\">" + child.getName()
                                                + "</li></ul>"; // 导航
                                        sb.append("<li class=\"active\"><a href=\"").append(child.getUrl())
                                                .append("?menuId=").append(child.getId())
                                                .append("\"><span class=\"fa ").append(child.getIcon())
                                                .append("\"></span> <span class=\"xn-text\">").append(child.getName())
                                                .append("</span></a></li>");
                                    } else {
                                        sb.append("<li><a href=\"").append(child.getUrl()).append("?menuId=")
                                                .append(child.getId()).append("\"><span class=\"fa ")
                                                .append(child.getIcon()).append("\"></span> <span class=\"xn-text\">")
                                                .append(child.getName()).append("</span></a></li>");
                                    }
                                }
                            }
                            sb.append("</ul>").append("</li>");
                        } else {
                            sb.append("<li class=\"xn-openable\"><a href=\"#\"><span class=\"fa ")
                                    .append(root.getIcon()).append("\"></span><span class=\"xn-text\">")
                                    .append(root.getName()).append("</span></a>").append("<ul>");
                            for (Menu child : children) {
                                if (roleMenuIds.contains(child.getId())) { // 权限筛�?
                                    sb.append("<li><a href=\"").append(child.getUrl()).append("?menuId=")
                                            .append(child.getId()).append("\"><span class=\"fa ")
                                            .append(child.getIcon()).append("\"></span> <span class=\"xn-text\">")
                                            .append(child.getName()).append("</span></a></li>");
                                }
                            }
                            sb.append("</ul>").append("</li>");
                        }
                    }
                }
            }
        }

        StringBuffer navBuffer = new StringBuffer();
        for (NavMenu navMenu : navMenus) {
            navBuffer.append("<li><a href=\"").append(Constants.baseUrl).append(navMenu.getUrl()).append("?")
                    .append("navId=").append(navMenu.getId()).append("\" class=\"act\"><img src=\"")
                    .append(navMenu.getIcon()).append("\" />").append("<span>").append(navMenu.getName())
                    .append("</span></a></li>");
        }
        request.setAttribute("username", adminUser.getName());
        request.setAttribute("navId", navId);
        request.setAttribute("navMenus", navBuffer.toString());
        request.setAttribute("navigation", navigation);
        request.setAttribute("leftMenus", sb.toString());
        // 处理显示日期,星期
        showDate(request);
        return currMenu;
    }

    /**
     * 显示日期,星期
     * 
     * @param request
     */
    public void showDate(HttpServletRequest request) {
        Date now = new Date();
        String year = DateUtils.toString(now, DateUtils.Y);
        String month = DateUtils.toString(now, DateUtils.M);
        String day = DateUtils.toString(now, DateUtils.D);
        String date = year + "年" + month + "月" + day + "日";
        String weekday = TimeUtil.getWeek(DateUtils.toString(now, DateUtils.YMD));
        request.setAttribute("currDate", date);
        request.setAttribute("currWeekDay", weekday);
    }

    /**
     * 用户session过期校验
     * 
     * @param request
     * @param response
     * @return
     */
    public AdminUser isSessionExpire(HttpServletRequest request, HttpServletResponse response) {
        AdminUser adminUser = (AdminUser) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER);
        if (null == adminUser || null == adminUser.getId()) {
            Subject subject = SecurityUtils.getSubject();
            if (subject.getSession() != null) {
                subject.logout();
            }
            String redirectUrl = Constants.baseUrl + "login";
            try {
                WebUtils.issueRedirect(request, response, redirectUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return adminUser;
    }
}
